# import re
#
# from rest_framework import serializers
#
# from rest_framework_jwt.serializers import jwt_payload_handler
# from rest_framework_jwt.serializers import jwt_encode_handler
# from . import models
#
#
# # 拿到前台token的两个函数: user >>>payload>>>token
#
# # 自定义序列化 和反序列化类
#
# class UserModelSerializer(serializers.ModelSerializer):
#     # 自定义反序列化字段:必须设置只参与发你序列化的(write_only)字段 序列化不会与model映射 只写写自己返回的字段
#     usr = serializers.CharField(write_only=True)
#     pwd = serializers.CharField(write_only=True)
#
#     # 只写字段放在下面也可
#     class Meta:
#         model = models.User
#         fields = ['usr', 'pwd','email','mobile','username']
#         extra_kwargs = {
#             'username': {
#                 'read_only': True
#             },
#             'mobile': {'read_only': True
#                        },
#             'email': {
#                 'read_only': True
#             }
#         }
#
#         # 局部钩子和全局钩子 看情况进行 使用 多的就用全局
#
#     def validate(self, attrs):
#         usr = attrs.get('usr')
#         pwd = attrs.get('pwd')
#
#         # 多种方式进行登录 请求的有手机 邮箱 用户名等登录方式
#         if re.match(r'.+@.+', usr):
#             user_query = models.User.objects.filter(email=usr)
#         elif re.match(r'^1[3-9][0-9]{9}$', usr):
#             user_query = models.User.objects.filter(mobile=usr)
#         else:
#             user_query = models.User.objects.filter(username=usr)
#         # 获取对
#         user_obj = user_query.first()
#         # print(user_obj, 333)
#
#         # 签发token :得到用户的登录,签发token并存储在实列化对象中
#         # 判断是否有用户和密码是否正确
#         if user_obj and user_obj.check_password(pwd):
#             # 将产生的token 放到我们实列化对象中
#             # (1) user_obj >>> payload >>>token
#             payload = jwt_payload_handler(user_obj)
#             # JWT_PAYLOAD_HANDLER
#             token = jwt_encode_handler(payload)
#
#             # 将当前的用户和签发的token 保存到实列化的 对象中
#
#             self.user = user_obj
#             self.token = token
#             print(self.token)
#             return attrs
#         # 异常
#         raise serializers.ValidationError({'data':'数据有误'})